package com.sum.slike.simple.slice;

import com.sum.slike.SuperLikeLayout;
import com.sum.slike.simple.BitmapProviderFactory;
import com.sum.slike.simple.CommentAdapter;
import com.sum.slike.simple.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;

import java.util.HashMap;
import java.util.LinkedHashMap;
/**
 * @author: zhu_zhonglin
 * @time: 2021/4/26
 */
public class RecyclerViewAbilitySlice extends AbilitySlice {

    private SuperLikeLayout superLikeLayout;
    private ListContainer container;
    private CommentAdapter commentAdapter;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_recycler_view);
        container = (ListContainer) findComponentById(ResourceTable.Id_container);
        commentAdapter = new CommentAdapter(this);
        commentAdapter.setAdapterItemListener(adapterItemListener);
        container.setItemProvider(commentAdapter);

        superLikeLayout = (SuperLikeLayout) findComponentById(ResourceTable.Id_super_like_layout);
        superLikeLayout.setProvider(BitmapProviderFactory.getHDProvider(this));
    }


    CommentAdapter.AdapterItemListener<Boolean> adapterItemListener = new CommentAdapter.AdapterItemListener<Boolean>() {
        long duration = 300;
        HashMap<Integer, Long> lastClickTimeMap = new LinkedHashMap<>();

        @Override
        public void onItemClickListener(Boolean isLike, int position, int id, Component v) {
            Long lastClickTime = lastClickTimeMap.get(position);
            if (lastClickTime == null || System.currentTimeMillis() - lastClickTime > duration) { // 防抖
                isLike = !isLike;
                commentAdapter.updateLikeStatusByPosition(isLike, position);
                if (!isLike) {
                    commentAdapter.updateLikeNumByPosition(isLike, position);
                }
                // 发起改变like状态的网络请求
            }
            lastClickTimeMap.put(position, System.currentTimeMillis());
            if (isLike) {
                commentAdapter.updateLikeNumByPosition(isLike, position);
                int[] itemPosition = v.getLocationOnScreen();
                int[] superLikePosition = superLikeLayout.getLocationOnScreen();
                int x = itemPosition[0] + v.getWidth() / 2;
                int y = (itemPosition[1] - superLikePosition[1]) + v.getHeight() / 2;
                superLikeLayout.launch(x, y);
            }
        }
    };

}
